package network.link;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.junit.Assert;
import org.junit.Test;

/**
 * JUnit test for Frame streams Input and Output
 */

public class FrameInputStreamTest {

  @Test
  public void testFrameInputStream() throws IOException {
    byte[] testbytes = {
        0, 1, 58, 120, 100, -128, 127, 127, 127, -128, 20, -128, -128, 127, 127, -128, 127, 127, -128, 1, -128, -128, -128, 127, 127, 127, -128};
    InputStream bytestream = new ByteArrayInputStream(testbytes);
    
    FrameInputStream fis = new FrameInputStream(bytestream);
    
    byte[][] expected = {
        {0, 1, 58, 120, 100},
        {20, -128, -128, 127, 127, 127, 127, 1, -128, -128},
        null,
        null};
    
    for (int i = 0; i < 4; ++i) {
      byte[] bytes = fis.read();
      Assert.assertArrayEquals("FrameInputStream fails", expected[i], bytes);
    }
    
  }
  
  @Test
  public void testFrameOutputStream() throws IOException {
    byte[] expected = {
        0, 1, 58, 120, 100, -128, 127, 127, 127, -128, 20, -128, -128, 127, 127, -128, 127, 127, -128, 1, -128, -128, -128, 127, 127, 127, -128};
    
    byte[][] testbytes = {
        {0, 1, 58, 120, 100},
        {20, -128, -128, 127, 127, 127, 127, 1, -128, -128}};
    ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
    
    FrameOutputStream fos = new FrameOutputStream(bytestream);
    
    for (int i = 0; i < 2; ++i) {
      fos.write(testbytes[i]);
    }
    
    Assert.assertArrayEquals("FrameOutputStream fails",
        expected,
        bytestream.toByteArray());
    
  }
  
  @Test
  public void testString() throws IOException {
    String[] messages = {
        "Hi! My name is Irvan Jahja! I'm very handsome you know...",
        "Please tell me why.",
        "You dont know? You're hopeless",
        "",
        "ah.."};
    
    //platform specific
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();
    
    FrameOutputStream fos = new FrameOutputStream(byteout);
    
    for (int i = 0; i < messages.length; ++i) {
      fos.write(messages[i].getBytes());
    }
    
    ByteArrayInputStream bytein = new ByteArrayInputStream(byteout.toByteArray());
    FrameInputStream fin = new FrameInputStream(bytein);
    for (int i = 0; i < messages.length; ++i) {
      byte[] baca = fin.read();
      System.out.println(new String(baca));
      Assert.assertEquals("Frame fail", messages[i], new String(baca));
    }
  }

}
